package com.openxt.nbzj.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.openxt.nbzj.R;
import com.openxt.nbzj.adapter.NewsWorkListAdapter;
import com.openxt.nbzj.adapter.ViewPagerAdapter;
import com.openxt.nbzj.fragment.OpenxtBaseActivity;
import com.openxt.nbzj.fragment.OpenxtFragment;
import com.openxt.nbzj.fragment.WorkFragment;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.search.SearchEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/**
 * Created by 颖杰_2 on 2016-07-19.
 */
public class NewsListActivity extends OpenxtBaseActivity implements RemotingEx.OnActionListener, View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener {

    @BindView(R.id.ptrClassicFrameLayout)
    PtrClassicFrameLayout ptrClassicFrameLayout;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.search_bar)
    LinearLayout search_bar;
    @BindView(R.id.search_btn)
    Button search_btn;
    @BindView(R.id.searchEditText)
    SearchEditText searchEditText;

    private Handler mHandler = new Handler();
    private RemotingModel remotingModel = null;
    private Context mContext = null;
    private boolean showSearchBar = false;
    private int pageIndex = 1;
    private int pageSize = 10;
    private Long timeStamp = null;
    private List<JSONObject> mNList = new ArrayList<>();
    private NewsWorkListAdapter newsWorkListAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setBaseStyle(R.layout.news_list_activity, "新闻模块");
        ButterKnife.bind(this);
        setActionUrl("#/newslist");
        mContext = this;
        remotingModel = new RemotingModel(mContext);

        setupRight();

        search_btn.setOnClickListener(this);
        searchEditText.addTextChangedListener(this);
        search_btn.setEnabled(false);

        newsWorkListAdapter = new NewsWorkListAdapter(mContext, mNList);
        listView.setAdapter(newsWorkListAdapter);
        listView.setOnItemClickListener(this);

        ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            pageIndex = 1;
                            timeStamp = null;
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                            doLoad();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            pageIndex++;
                            doLoadMore();
                        } catch (Exception e) {
                        }
                    }
                }, 10);
            }
        });

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    pageIndex = 1;
                    timeStamp = null;
                    doLoad();
                } catch (Exception e) {
                }
            }
        }, 10);
    }


    @Override
    public void onActionCompleted(String reVal, String actionName) {
        try {
            if (ConfigModel.NEWS_GETNATIVEFINDNEWS.equals(actionName) || (ConfigModel.NEWS_GETNATIVEFINDNEWS + "$more").equals(actionName)) {
                JSONObject data = JSON.parseObject(reVal);

                final int total = data.getInteger("total");
                timeStamp = data.getLong("timeStamp");
                JSONArray rows = data.getJSONArray("rows");
                if (ConfigModel.NEWS_GETNATIVEFINDNEWS.equals(actionName)) {
                    try {
                        mNList.clear();
                        newsWorkListAdapter.notifyDataSetChanged();
                        for (int i = 0, j = rows.size(); i < j; i++) {
                            mNList.add(rows.getJSONObject(i));
                        }
                        if (total > (pageIndex * pageSize))
                            ptrClassicFrameLayout.setLoadMoreEnable(true);
                        else
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                        listView.setAdapter(newsWorkListAdapter);
                    } finally {
                        ptrClassicFrameLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ptrClassicFrameLayout.refreshComplete();
                                newsWorkListAdapter.notifyDataSetChanged();
                            }
                        }, 0);
                    }
                } else if ((ConfigModel.NEWS_GETNATIVEFINDNEWS + "$more").equals(actionName)) {
                    try {
                        for (int i = 0, j = rows.size(); i < j; i++) {
                            mNList.add(rows.getJSONObject(i));
                        }
                        if (total > (pageIndex * pageSize))
                            ptrClassicFrameLayout.setLoadMoreEnable(true);
                        else
                            ptrClassicFrameLayout.setLoadMoreEnable(false);
                    } finally {
                        ptrClassicFrameLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (total > (pageIndex * pageSize))
                                    ptrClassicFrameLayout.loadMoreComplete(true);
                                else
                                    ptrClassicFrameLayout.loadMoreComplete(false);
                                newsWorkListAdapter.notifyDataSetChanged();
                            }
                        }, 0);
                    }
                }
            }
        }catch (Exception e){
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        if ((ConfigModel.NEWS_GETNATIVEFINDNEWS + "$more").equals(actionName)){
            pageIndex--;
        }
        if(actionName.startsWith(ConfigModel.NEWS_GETNATIVEFINDNEWS)) {
            ptrClassicFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ptrClassicFrameLayout.refreshComplete();
                }
            }, 0);
        }
    }

    private void setupRight() {
        LinearLayout right = getRight();
        right.setVisibility(View.VISIBLE);
        right.removeAllViews();

        View view = LayoutInflater.from(this).inflate(R.layout.right_btn, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        right.addView(view);

        ImageView btn = (ImageView)view.findViewById(R.id.right_btn);
        btn.setImageResource(R.mipmap.search);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputMethod();
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showSearchBar = !showSearchBar;
                        search_bar.setVisibility(showSearchBar ? View.VISIBLE : View.GONE);
                        searchEditText.setText("");
                    }
                }, 0);
            }
        });
    }

    private void doLoad(){
        try {
            String value = searchEditText.getText().toString();
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            param.put("type", "7");
            if(!StringUtil.isNull(value))
                param.put("title", value);
            remotingModel.getNewsGetnativefindnews(this, false, param, null);
        }catch (Exception e){

        }
    }

    private void doLoadMore(){
        try {
            String value = searchEditText.getText().toString();
            JSONObject param = new JSONObject();
            param.put("pageIndex", pageIndex);
            param.put("pageSize", pageSize);
            param.put("timeStamp", StringUtil.isNull(timeStamp) ? "" : timeStamp);
            param.put("type", "7");
            if(!StringUtil.isNull(value))
                param.put("title", value);
            remotingModel.getNewsGetnativefindnews(this, false, param, "$more");
        }catch (Exception e){

        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.search_btn) {
            hideInputMethod();
            if (ActivityUtil.isNetworkAvailable(mContext)) {
                ptrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ptrClassicFrameLayout.autoRefresh(true);
                    }
                }, 0);
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if(StringUtil.isNull(s))
            search_btn.setEnabled(false);
        else
            search_btn.setEnabled(true);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if (!ActivityUtil.isNetworkAvailable(mContext)) {
                showMsg("无网络，请先查看网络是否正常打开");
                return;
            }
            Utils.setLocalStorage(mContext, ConfigModel.NATIVE_PAGENAME, getActionUrl());
            Bundle bundle = new Bundle();
            JSONObject item = mNList.get(position);
            String RedirectURL = item.getString("RedirectURL");
            bundle.putString("url", ConfigModel.ROOTPATH + RedirectURL);
            toActivity(WebViewActivity.class, bundle, false);
        }catch (Exception e){

        }
    }
}
